package com.diandian.backend.dingding.exchange.controller;

import com.alibaba.fastjson2.JSON;
import com.diandian.backend.dingding.exchange.param.DingdingMessageSendParam;
import com.diandian.backend.dingding.exchange.service.DingdingTokenService;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import com.diandian.dingding.boot.starter.sender.DingDingTextMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/message")
public class DingdingMessageController {

    private static final Logger logger = LoggerFactory.getLogger(DingdingMessageController.class);

    @Autowired
    private DingDingTextMessageSender dingdingMessageService;

    @Autowired
    private DingdingTokenService dingdingTokenService;

    /**
     * 发送钉钉消息
     * @param data
     * @return
     */
    @PostMapping("/send/text")
    public BaseResult sendSms(@RequestHeader(value = "appKey") String appKey,
                              @RequestHeader(value = "appSecret") String appSecret,
                              @RequestBody DingdingMessageSendParam data) {

        logger.info("收到钉钉消息发送请求，数据：{}", JSON.toJSONString(data));

        data.check();

        // 获取token
        String token = null;
        try {
            token = dingdingTokenService.getToken(appKey, appSecret);
        } catch (Exception e) {
            logger.error("发送钉钉消息时，获取应用token异常...", e);
        }
        if(token == null || "".equals(token)){
            throw new DefaultException("未获取到令牌数据");
        }

        // 执行发送
        dingdingMessageService.sendTextMessageWithMobile(data.getContent(), data.getMobile(), token, data.getRobotAccessToken(), data.getRobotSecret());

        return new BaseResult(0, "success", null);
    }
}
